package com.yl.demo.base.exception;

import com.yl.demo.utils.Result;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 全局异常处理类
 * @author yl
 */
@ControllerAdvice
public class CtrlExceptionHandler {
    private static Logger logger = LoggerFactory.getLogger(CtrlExceptionHandler.class);

    /**
     * &#x62e6;&#x622a;&#x672a;&#x6388;&#x6743;&#x9875;&#x9762;
     * @param e
     * @return
     */
    @ResponseStatus(value = HttpStatus.FORBIDDEN)
    @ExceptionHandler(UnauthorizedException.class)
    public Result handleException(UnauthorizedException e) {
        logger.debug("UnauthorizedException===["+e.getMessage()+"]");
        Result result = new Result(403, "用户无权限");
        return result;
    }

    /**
     * 授权认证异常
     * @param e
     * @return
     */
    @ResponseStatus(value = HttpStatus.FORBIDDEN)
    @ExceptionHandler(AuthorizationException.class)
    public Result handleException2(AuthorizationException e) {
        logger.debug("AuthorizationException===["+e.getMessage()+"]");
        Result result = new Result(403, "授权认证异常");
        return result;
    }

    /**
     * 其它异常异常捕捉
     *
     *  ResponseBody 在返回自定义相应类的情况下必须有，这是@ControllerAdvice注解的规定
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result allException(Exception e) {
        logger.debug("allException===["+e.getMessage()+"]");
        e.printStackTrace();
        Result result = new Result(500, "系統异常");
        return result;
    }
}
